
package com.medical.controller;

import com.medical.entity.RegistrationEntity;
import com.medical.entity.dto.UpdateStatusDto;
import com.medical.service.RegistrationService;
import com.medical.tool.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Date;

@RestController
@RequestMapping("/registration")
public class RegistrationController {

    @Autowired
    private RegistrationService registrationService;

    @PostMapping("/add")
    public R add(@RequestBody RegistrationEntity registrationEntity) {
        try {
            registrationService.add(registrationEntity);
            return new R(200, "挂号成功");
        } catch (Exception e) {
            return new R(500, "挂号失败");
        }
    }

    /**
     * 根据userID获取挂号信息
     */
    @GetMapping("/getByUserId")
    public R getByUserId(@RequestParam Integer userId) {
        try {
            List<RegistrationEntity>  reg = registrationService.getOneByUserId(userId);
            return new R(200, "获取成功", reg);
        } catch (Exception e) {
            return new R(500, "获取失败");
        }
    }

    /**
     * 根据ID获取挂号信息
     */
    @GetMapping("/getById")
    public R getById(@RequestParam Integer reId) {
        try {
            RegistrationEntity reg = registrationService.getById(reId);
            return new R(200, "获取成功", reg);
        } catch (Exception e) {
            return new R(500, "获取失败");
        }
    }

    /**
     * 更新就诊状态并评分
     */
    @PutMapping("/updateStatus")
    public R updateStatus(@RequestBody UpdateStatusDto updateStatusDto) {
        try {
            // 仅允许从未就医状态转换
            RegistrationEntity reg = registrationService.getById(updateStatusDto.getReId());
            if (!"未就诊".equals(reg.getReStatus())) {
                return new R(400, "非法状态变更");
            }
            
            // 更新状态和评分
            reg.setReStatus(updateStatusDto.getReStatus());
            if ("已就诊".equals(updateStatusDto.getReStatus()) && updateStatusDto.getReStatus() != null) {
                reg.setReScore(updateStatusDto.getReScore());
            }
            registrationService.updateById(reg);
            return new R(200, "状态更新成功", reg);
        } catch (Exception e) {
            return new R(500, "状态更新失败");
        }
    }

    /**
     * 查询所有挂号信息
     */
    @GetMapping("/list")
    public R getList() {
        try {
            List<RegistrationEntity> registrations = registrationService.getAllRegistrations();
            // 检查并更新过期挂号状态
            registrations = registrationService.checkAndUpdateOverdueRegistrations(registrations);
            return new R(200, "查询成功", registrations);
        } catch (Exception e) {
            return new R(500, "查询失败");
        }
    }
}
